package com.miao.websecurity.config;

import com.alibaba.fastjson.JSON;
import com.miao.common.entity.R;
import com.miao.common.utils.JWTUtil;
import com.miao.common.utils.ResponseUtil;
import com.miao.websecurity.entity.TokenAdmin;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @author MiaoWenqing
 * @description: TODO
 * @date 2021/1/16 17:58
 */
public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {


    private final AuthenticationManager authenticationManager;


    public AuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager=authenticationManager;
        this.setPostOnly(true);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login", "POST"));
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        System.out.println("attemptAuthentication");
        String username = this.obtainUsername(request);
        username = username != null ? username : "";
        username = username.trim();
        String password = this.obtainPassword(request);
        password = password != null ? password : "";
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
        this.setDetails(request, authRequest);
        System.out.println(username+"---"+password);
        return this.authenticationManager.authenticate(authRequest);
    }


    //认证成功调用
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        System.out.println("successfulAuthentication");
        User authAdmin = (User) authResult.getPrincipal();

        TokenAdmin tokenAdmin = new TokenAdmin();
        tokenAdmin.setAdminId(Integer.valueOf(authAdmin.getUsername()));
        ArrayList<String> strings = new ArrayList<>();
        Collection<GrantedAuthority> authorities = authAdmin.getAuthorities();
        authorities.forEach(v->{
            strings.add(v.toString());
        });

        tokenAdmin.setRoles(strings);
        String token = JWTUtil.createToken(JSON.toJSONString(tokenAdmin));
        ResponseUtil.out(response,new R(2000,"success",token));

    }


    //认证失败调用
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        System.out.println("unsuccessfulAuthentication");
        ResponseUtil.out(response,new R(4000,"账号或密码错误",null));
    }
}
